package com.funny.learning.english.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.funny.learning.english.BaseActivity;
import com.funny.learning.english.R;
import com.funny.learning.english.api.BaseAjaxCallBack.IAjaxCallbackMMK;
import com.funny.learning.english.api.TiengAnhApi;
import com.funny.learning.english.util.ValidationUtil;

public class RegisterActivity extends BaseActivity {
	private Button btReg;
	private EditText edtEmail;
	private EditText edtRePass;
	private EditText edtPass;
	private EditText edtUser;
	private TextView tvMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_layout);
		initUI();

	}

	private void initUI() {
		btReg = (Button) findViewById(R.id.btReg);
		edtEmail = (EditText) findViewById(R.id.edtEmail);
		edtRePass = (EditText) findViewById(R.id.edtRePass);
		edtPass = (EditText) findViewById(R.id.edtPass);
		edtUser = (EditText) findViewById(R.id.edtUser);
		tvMessage = (TextView) findViewById(R.id.tvMessage);

		btReg.setOnClickListener(mBtnRegisterOnClickListener);

	}

	private IAjaxCallbackMMK mCallback = new IAjaxCallbackMMK() {

		@Override
		public <T> void handler(T t, int code) {
			// TODO Auto-generated method stub
			if (START == code) {
			} else if (COMPLETE == code) {
//				UserEntity userEntity = (UserEntity) t;
				
				Toast.makeText(activity, getString(R.string.register_success),
						Toast.LENGTH_LONG).show();

				Intent intent = new Intent(activity, LoginActivity.class);
//				intent.putExtra(Define.KEY_USER, userEntity);
				startActivity(intent);
			} else if (ERROR == code) {
				tvMessage.setText(getString(R.string.register_fail));
			}
		}
	};

	private void register() {
		String username = edtUser.getText().toString().trim();
		String pwd = edtPass.getText().toString().trim();
		String email = edtEmail.getText().toString().trim();
		String rePass = edtRePass.getText().toString().trim();

		if (!ValidationUtil.isValidUserName(username)) {
			tvMessage.setText(getString(R.string.register_err_acc));
			return;
		}

		if (!ValidationUtil.isValidPwd(pwd)) {
			tvMessage.setText(getString(R.string.register_err_pass));
			return;
		}

		if (!ValidationUtil.isValidEmail(email)) {
			tvMessage.setText(getString(R.string.register_err_email));
			return;
		}

		if (!ValidationUtil.isValidConfirm(pwd, rePass)) {
			tvMessage.setText(getString(R.string.register_not_is_pass));
			return;
		}

		TiengAnhApi.register(username, pwd, email, activity, mCallback);
	}

	private View.OnClickListener mBtnRegisterOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			register();
		}

	};
}
